<template>
  <div class="register-form">
    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="large"
      :show-label="false"
    >
      <n-form-item path="username">
        <n-input
          v-model:value="formData.username"
          placeholder="请输入用户名"
          :disabled="loading"
        >
          <template #prefix>
            <n-icon :size="18">
              <PersonOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <n-form-item path="password">
        <n-input
          v-model:value="formData.password"
          type="password"
          placeholder="请输入密码"
          :disabled="loading"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :size="18">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <n-form-item path="confirmPassword">
        <n-input
          v-model:value="formData.confirmPassword"
          type="password"
          placeholder="请确认密码"
          :disabled="loading"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :size="18">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <!-- 邮箱输入 -->
      <n-form-item path="email">
        <n-input
          v-model:value="formData.email"
          placeholder="请输入邮箱地址"
          :disabled="loading"
        >
          <template #prefix>
            <n-icon :size="18">
              <MailOutline />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>

      <!-- 点击验证码 -->
      <n-form-item>
        <ClickCaptcha
          @update:captcha-id="updateCaptchaId"
          @update:captcha-info="updateCaptchaInfo"
          @verified="handleCaptchaVerified"
          :disabled="loading"
        />
      </n-form-item>

      <!-- 邮箱验证码 -->
      <n-form-item path="captcha">
        <div class="captcha-container">
          <n-input
            v-model:value="formData.captcha"
            placeholder="请输入邮箱验证码"
            :disabled="loading"
          >
            <template #prefix>
              <n-icon :size="18">
                <ShieldCheckmarkOutline />
              </n-icon>
            </template>
          </n-input>
          <n-button
            :disabled="loading || countdown > 0 || !formData.email || !captchaVerified"
            :loading="sendingCode"
            @click="sendVerificationCode"
            class="send-code-btn"
            :title="`按钮状态: loading=${loading}, countdown=${countdown}, email=${!!formData.email}, captchaVerified=${captchaVerified}`"
          >
            {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
          </n-button>
        </div>
      </n-form-item>

      <!-- 用户协议 -->
      <n-form-item path="agreeTerms">
        <n-checkbox v-model:checked="formData.agreeTerms" :disabled="loading">
          我已阅读并同意
          <n-button text type="primary" @click="showTermsModal = true">
            《用户协议》
          </n-button>
          和
          <n-button text type="primary" @click="showPrivacyModal = true">
            《隐私政策》
          </n-button>
        </n-checkbox>
      </n-form-item>

      <n-button
        type="primary"
        size="large"
        block
        :loading="loading"
        @click="handleSubmit"
        class="submit-btn"
      >
        注册
      </n-button>
    </n-form>

    <div class="form-footer">
      <n-text depth="3">已有账号？</n-text>
      <n-button
        text
        type="primary"
        :disabled="loading"
        @click="$emit('switch-to-login')"
      >
        立即登录
      </n-button>
    </div>

    <!-- 用户协议模态框 -->
    <n-modal
      v-model:show="showTermsModal"
      preset="card"
      title="用户协议"
      style="width: 600px; max-width: 90vw;"
    >
      <div class="terms-content">
        <p>这里是用户协议的内容...</p>
        <!-- 实际项目中应该加载真实的用户协议内容 -->
      </div>
    </n-modal>

    <!-- 隐私政策模态框 -->
    <n-modal
      v-model:show="showPrivacyModal"
      preset="card"
      title="隐私政策"
      style="width: 600px; max-width: 90vw;"
    >
      <div class="privacy-content">
        <p>这里是隐私政策的内容...</p>
        <!-- 实际项目中应该加载真实的隐私政策内容 -->
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { sendEmailCode } from '@/api/user'
import { commonRules, createConfirmPasswordRules, agreeTermsRule, validateField } from '@/utils/validation'
import { generateRandomString } from '@/utils/auth'
import ClickCaptcha from '@/components/common/ClickCaptcha.vue'
import type { FormInst } from 'naive-ui'
import type { RegisterParams } from '@/types/user'
import {
  PersonOutline,
  LockClosedOutline,
  MailOutline,
  ShieldCheckmarkOutline
} from '@vicons/ionicons5'

interface Emits {
  (e: 'success'): void
  (e: 'switch-to-login'): void
}

const emit = defineEmits<Emits>()
const message = useMessage()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formData = reactive<RegisterParams & { confirmPassword: string; agreeTerms: boolean }>({
  tab: 'register',
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  captcha: '',
  registerType: 'email',
  mobile: '',
  captchaId: generateRandomString(),
  captchaInfo: '',
  agreeTerms: false
})

// 状态
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const showTermsModal = ref(false)
const showPrivacyModal = ref(false)
const captchaVerified = ref(false)

// 表单验证规则
const formRules = computed(() => ({
  username: commonRules.username,
  password: commonRules.password,
  confirmPassword: createConfirmPasswordRules(() => formData.password),
  email: commonRules.email,
  captcha: commonRules.captcha,
  agreeTerms: [agreeTermsRule]
}))

// 更新验证码ID
const updateCaptchaId = (id: string) => {
  formData.captchaId = id
}

// 更新验证码信息
const updateCaptchaInfo = (info: string) => {
  formData.captchaInfo = info
}

// 处理验证码验证成功
const handleCaptchaVerified = (verified: boolean) => {
  console.log('收到点击验证码验证状态变化:', verified)
  captchaVerified.value = verified
  console.log('captchaVerified.value 已更新为:', captchaVerified.value)
}

// 手动验证邮箱字段的备选方案
const validateEmailManually = async (email: string): Promise<boolean> => {
  try {
    const result = await validateField(email, commonRules.email)
    if (!result.valid) {
      message.error(result.message || '邮箱格式不正确')
      return false
    }
    return true
  } catch (error) {
    console.error('手动验证邮箱失败:', error)
    message.error('邮箱验证失败')
    return false
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  console.log('=== 发送验证码开始 ===')
  console.log('formRef.value:', formRef.value)
  console.log('formRef.value 类型:', typeof formRef.value)
  console.log('formRef.value 是否有 validate 方法:', formRef.value && typeof formRef.value.validate === 'function')
  console.log('captchaVerified.value:', captchaVerified.value)
  console.log('formData.email:', formData.email)
  console.log('formData.captchaId:', formData.captchaId)
  console.log('formData.captchaInfo:', formData.captchaInfo)

  // 检查点击验证码是否已验证
  if (!captchaVerified.value) {
    console.log('点击验证码未验证')
    message.error('请先完成点击验证码验证')
    return
  }

  // 验证邮箱字段 - 使用增强的验证逻辑
  try {
    console.log('开始验证邮箱字段')

    // 等待下一个 tick 确保组件完全渲染
    await nextTick()

    let emailValid = false

    // 首先尝试使用表单实例的 validate 方法
    if (formRef.value && typeof formRef.value.validate === 'function') {
      try {
        console.log('使用表单实例验证邮箱')
        await formRef.value.validate(undefined, (rule) => rule.key === 'email')
        emailValid = true
        console.log('表单实例验证邮箱成功')
      } catch (error) {
        console.log('表单实例验证邮箱失败，尝试手动验证:', error)
        emailValid = await validateEmailManually(formData.email)
      }
    } else {
      console.log('表单实例不可用或 validateField 方法不存在，使用手动验证')
      emailValid = await validateEmailManually(formData.email)
    }

    if (!emailValid) {
      console.log('邮箱验证失败')
      return
    }

    console.log('邮箱字段验证通过')
  } catch (error) {
    console.log('邮箱字段验证过程出错:', error)
    return
  }

  try {
    sendingCode.value = true
    console.log('开始发送邮箱验证码')

    // 发送邮箱验证码，需要传递点击验证码信息
    const result = await sendEmailCode(formData.email, 'user_register', {
      captchaId: formData.captchaId!,
      captchaInfo: formData.captchaInfo!
    })

    console.log('发送邮箱验证码结果:', result)
    message.success(result.message || '验证码已发送到您的邮箱，请注意查收')
    startCountdown()
  } catch (error: any) {
    console.error('发送验证码失败:', error)
    message.error(error.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    await userStore.register(formData)
    emit('success')
  } catch (error: any) {
    console.error('注册失败:', error)
    message.error(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-form {
  padding: 8px 0;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-container .n-input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 100px;
}

.submit-btn {
  margin-top: 8px;
  border-radius: 8px;
  font-weight: 500;
}

.form-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--n-border-color);
}

.terms-content,
.privacy-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 16px 0;
  line-height: 1.6;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .captcha-container {
    gap: 8px;
  }
  
  .send-code-btn {
    min-width: 80px;
    font-size: 12px;
  }
  
  .form-footer {
    margin-top: 20px;
    padding-top: 12px;
  }
}
</style>
